package com.example.pos_terminal;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import bean.AraStoreLog;
import bean.ItemPriceAccountModel;
import bean.ResultEntity;
import bean.TradeAccountConsumptionFlow;
import bean.TradeConsumptionDetail;
import bean.TradeConsumptionMain;
import config.ApiClient;
import config.CommonValue;
import config.QYRestClient;
import db.TaskManager;
import tools.AppException;
import tools.GsonTools;
import tools.ListUtils;
import tools.TimeTools;

import static com.example.pos_terminal.MainActivity.timeStop;
import static tools.GetMacAddress.getMacAddress;

public class GenerateOrder {
    private TaskManager taskManager;
    private MainActivity mainActivity;
    private UploadThread uploadThread;
    private OrderThread orderThread;
    private  List<AraStoreLog> uploadAraStoreLog;
    private  List<TradeAccountConsumptionFlow> uploadConsumptionFlow;
    private int count = 0;
    private int sum = 0;
    private X5WebView webView;
    boolean isTRUE= true;

    List<List<AraStoreLog>> partition = null;

    public   GenerateOrder(TaskManager taskManagers,MainActivity mainActivity){
        this.taskManager = taskManagers;
        this.mainActivity = mainActivity;
        this.webView = mainActivity.getWebView();
        ExecutorService cacheThreadPool = Executors.newCachedThreadPool();
    }
    @JavascriptInterface
    public int insertOrder(String log, String maps){
        Gson gson = new Gson();
       List<ItemPriceAccountModel> modelList = gson.fromJson(maps, new TypeToken<List<ItemPriceAccountModel>>() {}.getType());
        AraStoreLog araStoreLog = gson.fromJson(log, new TypeToken<AraStoreLog>() {
        }.getType());
        araStoreLog.setCreateTime(TimeTools.calendar2String(Calendar.getInstance()));
        int i = taskManager.payInsertAraStoreLog(araStoreLog, modelList, true);
        return i;
    }
    @JavascriptInterface
    public void updateOrder(String orderNo, String logId,String beforeAmount,String afterAmount){
        List<TradeConsumptionMain> tradeConsumptionMains = taskManager.listTradeMainByOrderStatus(orderNo);
        if (tradeConsumptionMains!=null&&tradeConsumptionMains.size()==1) {
            taskManager.updateStatusMain(tradeConsumptionMains.get(0).getFlowNo(), logId,beforeAmount,afterAmount);
        }
        ExecutorService executorService = Executors.newCachedThreadPool();
            Runnable syncRunnable = new Runnable() {
                @Override
                public void run() {
                    //正常在这加入实时同步
                    Calendar Time1 = TimeTools.startOfDay(Calendar.getInstance(), null);
                    Calendar Time2 = TimeTools.endOfDay(Calendar.getInstance(), null);
                    String startTime = TimeTools.calendar2String(Time1);
                    String endTime = TimeTools.calendar2String(Time2);
                    uploadTaskTime(startTime,endTime,orderNo);
                }
            };
            executorService.execute(syncRunnable);
    }


    @JavascriptInterface
    public String getOrderByCard(String card,String customerNo){
        Gson gson = new Gson();
        Calendar Time1 = TimeTools.startOfDay(Calendar.getInstance(), null);
        Calendar Time2 = TimeTools.endOfDay(Calendar.getInstance(), null);
        String startTime = TimeTools.calendar2String(Time1);
        String endTime = TimeTools.calendar2String(Time2);
        List<TradeAccountConsumptionFlow> tradeAccountConsumptionFlows = taskManager.getConsumptionFlow(startTime,endTime,card,customerNo);
        String s = gson.toJson(tradeAccountConsumptionFlows);
        return s;
    }
    @JavascriptInterface
    public String getOrderByStatus(){
        List<TradeConsumptionMain> mains = taskManager.listTradeTaskByOrderStatus();
        Gson gson = new Gson();
        String s = gson.toJson(mains);
        return s;
    }
    @JavascriptInterface
    public String getaraStoreLog(String flowNo){
        AraStoreLog araStoreLog = taskManager.queryAraStoreLog(flowNo);
        Gson gson = new Gson();
        String s = gson.toJson(araStoreLog);
        return s;
    }
    @JavascriptInterface
    public void exit(boolean isOk){

    }
    @JavascriptInterface
    public void uploadOrder(){
        if (uploadThread==null){
            uploadThread = new UploadThread();
        }
        if (timeStop){
            uploadThread.run();
        }else{
            Toast t = Toast.makeText(mainActivity, "自动上传中,请勿手动上传", Toast.LENGTH_SHORT);
            LinearLayout layout = (LinearLayout) t.getView();
            TextView tv = (TextView) layout.getChildAt(0);
            tv.setTextSize(25);
            t.show();
            webView.post(() -> webView.loadUrl("javascript:FnOrder(false)"));
        }

    }
    @JavascriptInterface
    public void deleteOldData(){
        taskManager.deleteOldData();
        Toast t =  Toast.makeText(mainActivity,"历史数据清除成功",Toast.LENGTH_SHORT);
        LinearLayout layout = (LinearLayout) t.getView();
        TextView tv = (TextView) layout.getChildAt(0);
        tv.setTextSize(25);
        t.show();
        webView.post(() -> webView.loadUrl("javascript:FnOrder(false)"));
    }

    private class UploadThread extends Thread{
        @Override
        public void run() {
            super.run();

            Calendar pveTime = TimeTools.startOfDay(Calendar.getInstance(), null);
            Calendar nextTime = (Calendar)pveTime.clone();
            pveTime.add(Calendar.DAY_OF_YEAR, -4);
            for (int x=0;x<2;x++){
                String startTime = TimeTools.calendar2String(pveTime);
                pveTime.add(Calendar.DAY_OF_YEAR, 1);
                nextTime = ((Calendar) pveTime.clone());
                String endTime = TimeTools.calendar2String(nextTime);
                uploadTask(startTime, endTime,null);
            }
            Toast t = Toast.makeText(mainActivity, "上传完成", Toast.LENGTH_SHORT);
            LinearLayout layout = (LinearLayout) t.getView();
            TextView tv = (TextView) layout.getChildAt(0);
            tv.setTextSize(25);
            t.show();
            webView.post(() -> webView.loadUrl("javascript:FnOrder(false)"));
        }
    }


    private void uploadTaskTime(String startTime, String endTime,String flowNo) {
        uploadConsumptionFlow = taskManager.queryUploadConsumptionFlow( startTime, endTime, flowNo);
        if (uploadConsumptionFlow.size()>0){
//            processUploadFlow();
            processUploadFlowMain();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
//        uploadAraStoreLog = taskManager.queryUploadAraStoreLog(startTime, endTime);
//        if (uploadAraStoreLog.size() > 0) {
//            processUploadAraLog();
//            try {
//                Thread.sleep(3000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }

    }

    private void uploadTask(String startTime, String endTime,String flowNo) {
//        uploadConsumptionFlow = taskManager.queryUploadConsumptionFlow( startTime, endTime, flowNo);
//        if (uploadConsumptionFlow.size()>0){
//
////            processUploadFlow();
//            processUploadFlowMain();
//            try {
//                Thread.sleep(3000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }


        uploadAraStoreLog = taskManager.queryUploadAraStoreLog(startTime, endTime);
        if (uploadAraStoreLog.size() > 0) {
            processUploadAraLog();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private void processUploadFlowMain() {
        final Message message = new Message();
        String timeString = uploadConsumptionFlow.get(0).getCreateTime().substring(0,10);
        for (TradeAccountConsumptionFlow flow:uploadConsumptionFlow) {
            List<TradeConsumptionMain>  mains = taskManager.listTradeTask(flow.getFlowNo());
//            uploadConsumptionMain.addAll(mains);
            flow.setMainLists(mains);
        }
        List<List<TradeAccountConsumptionFlow>> partition = ListUtils.partition(uploadConsumptionFlow, 50);
        for (List<TradeAccountConsumptionFlow> tradeAccountConsumptionFlows : partition) {
            RequestParams params = new RequestParams();
            params.add("uploadConsumptionFlow", GsonTools.toJson(uploadConsumptionFlow));
//        String SerialNumber = Build.SERIAL;
//        SerialNumber = "2fe1a0ce";
            params.add("macAddress",getMacAddress());
            final List<TradeAccountConsumptionFlow> flowList = uploadConsumptionFlow;
            QYRestClient.muchPost("uploadFlowTask.do", params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    String res = new String(responseBody).trim();
                    Log.e("TEST", "uploadFlow onSuccess: " + res);
                    ResultEntity resultEntity = null;
                    try {
                        resultEntity = GsonTools.parse(res, ResultEntity.class);
                    } catch (AppException e) {
                        e.printStackTrace();
                    }
                    if (CommonValue.OPT_OK == resultEntity.getResult()){
                        String data = resultEntity.getData();
                        List<String> okFlowLists = new Gson().fromJson(data, new TypeToken<List<String>>(){}.getType());
                        if (okFlowLists != null && okFlowLists.size() > 0) {
                            taskManager.updateStatusFlow(uploadConsumptionFlow, okFlowLists);
                            if (Looper.myLooper()==null)
                                Looper.prepare();
                            Toast t =  Toast.makeText(mainActivity,okFlowLists.get(0) +"订单上传成功",Toast.LENGTH_SHORT);
                            LinearLayout layout = (LinearLayout) t.getView();
                            TextView tv = (TextView) layout.getChildAt(0);
                            tv.setTextSize(25);
                            t.show();
                            Looper.loop();
                        }

                    }
                }
                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable throwable) {
                    Toast t = Toast.makeText(mainActivity, timeString + "日订单上传失败", Toast.LENGTH_SHORT);
                    LinearLayout layout = (LinearLayout) t.getView();
                    TextView tv = (TextView) layout.getChildAt(0);
                    tv.setTextSize(25);
                    t.show();
                    Log.e("TEST", "uploadFlow onFailure: " + statusCode);
                }
            });
        }
    }

    /**
     * 处理微信log表数据上传
     *
     */
    private void processUploadAraLog() {
//        uploadAraStoreLog = taskManager.queryUploadAraStoreLog();
        Log.e("log上传",uploadAraStoreLog.size()+"");
        //数据太大做切割
        if (partition==null) {
            partition   = ListUtils.partition(uploadAraStoreLog, 50);
        }
        final Message message = new Message();

        if (partition.size()>0) {
//            if (isTRUE){
//                isTRUE =false;
                RequestParams params = new RequestParams();
                params.add("uploadAraStoreLog", GsonTools.toJson(partition.get(0)));
                QYRestClient.muchPost("uploadAraStoreLogTask.do", params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        String res = new String(responseBody).trim();
                        Log.e("TEST", "uploadAraStoreLog onSuccess: " + res);

                        ResultEntity resultEntity = null;
                        try {
                            resultEntity = GsonTools.parse(res, ResultEntity.class);
                        } catch (AppException e) {
                            e.printStackTrace();
                        }

                        if (CommonValue.OPT_OK == resultEntity.getResult()){
                            String data = resultEntity.getData();
                            List<String> okOrderNoLists = new Gson().fromJson(data, new TypeToken<List<String>>(){}.getType());

                            taskManager.updateStatusAraLog(uploadAraStoreLog, okOrderNoLists);
//                            isTRUE = true;
                            mainActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                     partition.remove(0);
                                }
                            });
                            processUploadAraLog();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable throwable) {
                        Log.e("TEST", "uploadAraStoreLog onFailure: " + statusCode);
                        count++;
                        checkCounts();
                    }
                });
//            }else{
//                    //啥也不做
//            }
        }
    }

    private void checkCounts(){
        Log.e("TEST", "checkCounts: " + count);
        if (count == 2) {
            count = 0;

            if ((uploadConsumptionFlow != null && uploadConsumptionFlow.size() == 0)
                    && (uploadAraStoreLog != null && uploadAraStoreLog.size() == 0)) {
            } else {
            }
        }
    }

    @JavascriptInterface
    public void orderThread(){
        if (orderThread==null){
            orderThread = new OrderThread();
        }
        orderThread.run();
    }
    private class OrderThread extends Thread{
        @Override
        public void run() {
            super.run();
            orderComparison();

        }
    }
    private void orderComparison() {
        List<TradeConsumptionMain> mains = taskManager.listTradeTaskByOrderStatus();
//            uploadConsumptionMain.addAll(mains);
        if (mains!=null) {
            for (final TradeConsumptionMain tMain : mains) {
                final RequestParams params = new RequestParams();
                List<TradeConsumptionDetail> detailLists = tMain.getDetailLists();

                params.add("out_trade_no", tMain.getFlowNo());//商户订单号自己生成
                Map map= new HashMap<String,String>();
                params.add("reason", tMain.getReason());
                ApiClient.alipayQuery( params, new ApiClient.ClientCallback() {
                    @Override
                    public void onSuccess(Object data) {

                        Log.e("test", "dismissProgress 1");
                        Map<String, String> microPay = (Map<String, String>) data;
                        String is_success = microPay.get("is_success");
                        AraStoreLog araStoreLog = taskManager.queryAraStoreLog(tMain.getFlowNo());
                        if (is_success.equals("YES")||is_success.equals("支付成功，但订单未打印")) {

                            if (is_success.equals("支付成功，但订单未打印")){
                                tMain.setPrintStatus("0");
                            }
                            String order = microPay.get("order");
                            List<TradeConsumptionMain> tradeConsumptionMains = taskManager.listTradeMainByOrderStatus(tMain.getFlowNo());
                            if (tradeConsumptionMains!=null&&tradeConsumptionMains.size()==1){
                                    taskManager.updateStatusMain(tradeConsumptionMains.get(0).getFlowNo(), araStoreLog.getId(),"","");
                            }
                        } else if (is_success.equals("NO")) {
                            taskManager.deleteFailedOrder(tMain.getFlowNo());
                            //taskManager.insertAraStoreLog(araLog,listModel,microPay);//测试用
//                            showToast("支付失败，请重新扫码!");
                            Log.e("查询结果：支付失败", "============111");
                        } else {
                            //taskManager.insertAraStoreLog(araLog,listModel,microPay);//测试用
                            //                            showToast("支付失败，请重新扫码!");
                            Log.e("支付失败", "============222");
                        }
                    }

                    @Override
                    public void onFailure(String message) {
                        Log.e("test", "dismissProgress 3");
//                        showToast(message);
                        Log.e("支付请求失败", "============333");
                    }
                });
            }
            Toast t =  Toast.makeText(mainActivity, "订单对比成功",Toast.LENGTH_SHORT);
            LinearLayout layout = (LinearLayout) t.getView();
            TextView tv = (TextView) layout.getChildAt(0);
            tv.setTextSize(25);
            t.show();
        }

    }


}
